const Tag = require('../models/tag')
const setOutput = require('../tools/setOutput').setOutput
// const standardObj = require('../tools/setOutput').standardObj
class TagController {
  prefix = '' 
  getPath(name){
    return name ? `/${this.prefix}/${name}` : `/${this.prefix}`
  }  

  async find(ctx, next) {
    const {page = 1, pageSize = 20} = ctx.request.query 
    const total = await Tag.count({})
    const list = await Tag.find().skip((parseInt(page) - 1) * parseInt(pageSize)).limit(parseInt(pageSize) || 5).lean() 
    const data = {
      list: list,
      total: total
    }
    ctx.response.body = setOutput(data, 'fetch')
  }

  async add(ctx, next) {
    ctx.verifyParams({
      label: {type: 'string', required: true}
    })
    const obj = ctx.request.body
    const [err, data] = await to(Tag.find({label: obj.label}))
    if (data.length) {
      return ctx.throw(500, '此标签名已经被创建了，请换一个名字吧！')
    }
    const [addErr, res] = await to(new Tag(obj).save())
    if(addErr) return ctx.throw(500, err) 
    
    ctx.response.body = setOutput(res.toJSON())
  }

  async update(ctx, next) {
    ctx.verifyParams({
      id: { type: "string", required: true },
      label: { type: "string", required: true }
    })
    const obj = {...ctx.request.body} 
    const [err, data] = await to( Tag.findByIdAndUpdate(obj.id, obj, { new: true }).lean() ) 
    if(err || !data) return ctx.throw(500, err) 
    ctx.response.body = setOutput(data, 'update')
  }

  async delete(ctx, next) {
    const [err, data] = await to( Tag.deleteOne({ _id: ctx.params.id }) )
    if(err) return ctx.throw(500, err) 
    ctx.response.body = {
      data: null,
      code: 0,
      msg: '成功'
    }
  }
  /*
  async findByUser(ctx, next) {
    const list = await Tag.find({
      articles: { 
        $elemMatch: {
          createId: {$eq: userInfo._id}
        } 
      }
    }).lean()
    // console.log('list', list)
    const tags = list.map((item) => {
      const obj = {
        ...item
      }
      obj.articles = obj.articles.filter((article) => {
        return article.createId === userInfo._id
      })
      return standardObj(obj)
    })
    // console.log(tags)
    ctx.response.body = {
      data: tags,
      code: 0,
      msg: '成功'
    }
  }
  */
}

module.exports = new TagController()